package com.jwgf.Half485.fxthreadpool;

import com.android.Samkoonhmi.serial.SerialPort;
import com.jwgf.comlibrary.Half485Manager;

import java.util.concurrent.Callable;

public class FxCallable implements Callable<FxData> {
    private static final int REPEAT_TIME = 2;
    private byte[] send;

    public FxCallable(byte[] send) {
        this.send = send;
    }

    @Override
    public FxData call() throws Exception {
        if (send != null) {
            for (int i = 0; i < REPEAT_TIME; ++i) {
                Half485Manager.getInstance().write1(send);
                byte[] recv = Half485Manager.getInstance().read1(50);
                String cmdType = FxUtils.checkCmdType(send);
                int len = FxUtils.getReturnByteLen(send);
                if(cmdType.equals(FxUtils.WR)) {
                    if (recv != null && recv.length == len) {
                        if (FxUtils.sumCheck(recv)) {
                            //通讯成功
                            FxData fxData = new FxData();
                            fxData.send = send;
                            fxData.recv = recv;
                            fxData.isDone = true;
                            return fxData;
                        } else {
                            //失败
                            continue;
                        }


                    } else {
                        // 失败
                        continue;
                    }
                } else if (cmdType.equals(FxUtils.WW)){
                    if (recv != null && recv.length >= 4) {
                        if (FxUtils.writeACK(send, recv)) {
                            //通讯成功
                            FxData fxData = new FxData();
                            fxData.send = send;
                            fxData.recv = recv;
                            fxData.isDone = true;
                            return fxData;
                        }
                    } else {
                        //失败
                        continue;
                    }
                }

            }
            // 通讯失败
            FxData fxData = new FxData();
            fxData.send = send;
            fxData.isDone = false;
            return fxData;
        }
        return null;
    }
}
